// 数据同步系统 - 负责跨页面数据同步和冲突解决
class SyncSystem {
    constructor() {
        // 检查核心依赖是否可用
        if (!window.dataManager) {
            console.warn('数据管理器未初始化，同步系统将使用基础功能');
            this.dataManager = this.createFallbackDataManager();
        } else {
            this.dataManager = window.dataManager;
        }
        
        this.syncChannels = new Map();
        this.conflictResolution = {
            strategy: 'last-write-wins', // 'last-write-wins', 'merge', 'manual'
            mergeStrategies: {
                'metrics': 'sum',
                'charts': 'replace',
                'system': 'prefer-newer'
            }
        };
        this.syncHistory = [];
        this.isInitialized = false;
        
        try {
            this.init();
            this.isInitialized = true;
        } catch (error) {
            console.error('同步系统初始化失败:', error);
            this.initWithFallback();
        }
    }

    // 创建回退数据管理器
    createFallbackDataManager() {
        return {
            getState: (path) => {
                console.log(`回退数据管理器获取状态: ${path}`);
                // 从 localStorage 获取数据
                const stored = localStorage.getItem(`sync-${path}`);
                return stored ? JSON.parse(stored) : null;
            },
            setState: (path, value) => {
                console.log(`回退数据管理器设置状态: ${path}`);
                // 存储到 localStorage
                localStorage.setItem(`sync-${path}`, JSON.stringify(value));
                return Promise.resolve();
            },
            subscribe: (path, callback) => {
                console.log(`回退数据管理器订阅: ${path}`);
                // 简单的定时器模拟订阅
                const interval = setInterval(() => {
                    const value = this.createFallbackDataManager().getState(path);
                    if (value) callback(value, { source: 'fallback' });
                }, 5000); // 每5秒检查一次
                
                return () => clearInterval(interval);
            }
        };
    }

    // 使用回退机制初始化
    initWithFallback() {
        console.warn('使用回退机制初始化同步系统');
        this.setupBasicSync();
        this.isInitialized = true;
        console.log('同步系统回退模式已初始化');
    }

    // 设置基础同步功能
    setupBasicSync() {
        // 基础的数据同步功能
        this.subscribers = new Map();
        
        // 监听 localStorage 变化作为基础同步机制
        window.addEventListener('storage', (event) => {
            if (event.key && event.key.startsWith('sync-')) {
                const path = event.key.replace('sync-', '');
                const value = event.newValue ? JSON.parse(event.newValue) : null;
                this.notifySubscribers(path, value);
            }
        });
    }

    // 通知订阅者
    notifySubscribers(path, value) {
        const subscribers = this.subscribers.get(path) || [];
        subscribers.forEach(callback => {
            try {
                callback(value, { source: 'basic-sync' });
            } catch (error) {
                console.error('通知订阅者失败:', error);
            }
        });
    }

    // 初始化同步系统
    init() {
        this.setupBroadcastChannel();
        this.setupStorageListener();
        this.setupSyncMonitoring();
        console.log('数据同步系统已初始化');
    }

    // 设置广播通道（用于跨标签页通信）
    setupBroadcastChannel() {
        try {
            this.broadcastChannel = new BroadcastChannel('dashboard-sync');
            this.broadcastChannel.addEventListener('message', (event) => {
                this.handleBroadcastMessage(event.data);
            });
        } catch (error) {
            console.warn('BroadcastChannel 不支持，使用 localStorage 回退');
            this.useLocalStorageFallback = true;
        }
    }

    // 设置存储监听器
    setupStorageListener() {
        window.addEventListener('storage', (event) => {
            if (event.key === 'dashboard-sync-event' && event.newValue) {
                this.handleStorageEvent(JSON.parse(event.newValue));
            }
        });
    }

    // 设置同步监控
    setupSyncMonitoring() {
        // 监控同步状态
        setInterval(() => {
            this.checkSyncHealth();
        }, 30000); // 每30秒检查一次
    }

    // 处理广播消息
    handleBroadcastMessage(message) {
        if (message.type === 'data-update') {
            this.handleRemoteUpdate(message.data);
        } else if (message.type === 'sync-request') {
            this.handleSyncRequest(message);
        } else if (message.type === 'conflict-resolution') {
            this.handleConflictResolution(message);
        }
    }

    // 处理存储事件
    handleStorageEvent(event) {
        if (this.useLocalStorageFallback) {
            this.handleBroadcastMessage(event);
        }
    }

    // 处理远程更新
    async handleRemoteUpdate(update) {
        console.log('收到远程更新:', update);
        
        try {
            // 检查冲突
            const conflict = await this.checkForConflict(update);
            
            if (conflict) {
                await this.resolveConflict(conflict, update);
            } else {
                await this.applyUpdate(update);
            }
            
            this.recordSyncEvent('update-applied', update);
            
        } catch (error) {
            console.error('处理远程更新失败:', error);
            this.recordSyncEvent('update-failed', { update, error });
        }
    }

    // 检查冲突
    async checkForConflict(update) {
        const currentValue = this.dataManager.getState(update.path);
        
        // 如果路径不存在，没有冲突
        if (currentValue === undefined) return null;
        
        // 检查时间戳冲突
        if (update.timestamp && currentValue.timestamp) {
            const timeDiff = Math.abs(update.timestamp - currentValue.timestamp);
            if (timeDiff < 5000) { // 5秒内的冲突
                return {
                    type: 'timestamp',
                    path: update.path,
                    currentValue,
                    update,
                    currentTimestamp: currentValue.timestamp,
                    updateTimestamp: update.timestamp
                };
            }
        }
        
        // 检查值冲突
        if (JSON.stringify(currentValue) !== JSON.stringify(update.value)) {
            return {
                type: 'value',
                path: update.path,
                currentValue,
                update
            };
        }
        
        return null;
    }

    // 解决冲突
    async resolveConflict(conflict, update) {
        console.log('检测到冲突，正在解决:', conflict);
        
        const strategy = this.conflictResolution.strategy;
        
        switch (strategy) {
            case 'last-write-wins':
                return await this.resolveLastWriteWins(conflict, update);
                
            case 'merge':
                return await this.resolveMerge(conflict, update);
                
            case 'manual':
                return await this.resolveManual(conflict, update);
                
            default:
                console.warn('未知冲突解决策略，使用 last-write-wins');
                return await this.resolveLastWriteWins(conflict, update);
        }
    }

    // 最后写入者获胜策略
    async resolveLastWriteWins(conflict, update) {
        if (update.timestamp > conflict.currentTimestamp) {
            await this.applyUpdate(update);
            this.recordSyncEvent('conflict-resolved-lww', { conflict, update });
        }
    }

    // 合并策略
    async resolveMerge(conflict, update) {
        const mergeStrategy = this.conflictResolution.mergeStrategies[conflict.path.split('.')[0]] || 'replace';
        
        let mergedValue;
        
        switch (mergeStrategy) {
            case 'sum':
                mergedValue = this.mergeSum(conflict.currentValue, update.value);
                break;
                
            case 'average':
                mergedValue = this.mergeAverage(conflict.currentValue, update.value);
                break;
                
            case 'prefer-newer':
                mergedValue = update.timestamp > conflict.currentTimestamp ? update.value : conflict.currentValue;
                break;
                
            default: // 'replace'
                mergedValue = update.value;
        }
        
        await this.dataManager.setState(update.path, mergedValue);
        this.recordSyncEvent('conflict-resolved-merge', { conflict, update, mergedValue });
    }

    // 手动解决策略
    async resolveManual(conflict, update) {
        // 显示冲突解决界面
        this.showConflictResolutionUI(conflict, update);
    }

    // 应用更新
    async applyUpdate(update) {
        await this.dataManager.setState(update.path, update.value);
        
        // 通知其他组件
        this.notifySubscribers(update);
    }

    // 通知订阅者
    notifySubscribers(update) {
        // 通过数据管理器通知订阅者
        this.dataManager.notifySubscribers(update.path, update.value);
    }

    // 发送同步请求
    async sendSyncRequest(targetPage, data) {
        const message = {
            type: 'sync-request',
            source: 'dashboard',
            target: targetPage,
            data: data,
            timestamp: Date.now()
        };
        
        this.broadcastMessage(message);
    }

    // 广播消息
    broadcastMessage(message) {
        if (this.broadcastChannel) {
            this.broadcastChannel.postMessage(message);
        } else if (this.useLocalStorageFallback) {
            // 使用 localStorage 作为回退
            localStorage.setItem('dashboard-sync-event', JSON.stringify(message));
            // 触发 storage 事件
            window.dispatchEvent(new StorageEvent('storage', {
                key: 'dashboard-sync-event',
                newValue: JSON.stringify(message)
            }));
        }
    }

    // 处理同步请求
    handleSyncRequest(request) {
        if (request.target === 'dashboard') {
            this.respondToSyncRequest(request);
        }
    }

    // 响应同步请求
    async respondToSyncRequest(request) {
        const response = {
            type: 'sync-response',
            source: 'dashboard',
            target: request.source,
            data: await this.getSyncData(request.data),
            timestamp: Date.now()
        };
        
        this.broadcastMessage(response);
    }

    // 获取同步数据
    async getSyncData(request) {
        const data = {};
        
        if (request.includeMetrics) {
            data.metrics = this.dataManager.getState('metrics');
        }
        
        if (request.includeCharts) {
            data.charts = this.dataManager.getState('charts');
        }
        
        if (request.includeSystem) {
            data.system = this.dataManager.getState('system');
        }
        
        return data;
    }

    // 处理冲突解决
    handleConflictResolution(message) {
        // 实现冲突解决逻辑
        console.log('处理冲突解决:', message);
    }

    // 记录同步事件
    recordSyncEvent(type, data) {
        const event = {
            type,
            data,
            timestamp: Date.now(),
            page: 'dashboard'
        };
        
        this.syncHistory.push(event);
        
        // 保持历史记录大小
        if (this.syncHistory.length > 100) {
            this.syncHistory.shift();
        }
        
        // 触发事件
        this.emitSyncEvent(event);
    }

    // 触发同步事件
    emitSyncEvent(event) {
        const customEvent = new CustomEvent('sync-event', {
            detail: event
        });
        
        window.dispatchEvent(customEvent);
    }

    // 检查同步健康状态
    checkSyncHealth() {
        const now = Date.now();
        const recentEvents = this.syncHistory.filter(event => 
            now - event.timestamp < 60000 // 1分钟内的事件
        );
        
        const errorCount = recentEvents.filter(event => 
            event.type.includes('failed') || event.type.includes('error')
        ).length;
        
        const healthStatus = {
            isHealthy: errorCount < 3,
            errorCount,
            recentEventCount: recentEvents.length,
            lastSync: this.syncHistory.length > 0 ? 
                this.syncHistory[this.syncHistory.length - 1].timestamp : null
        };
        
        if (!healthStatus.isHealthy) {
            console.warn('同步系统健康状态异常:', healthStatus);
            this.emitSyncEvent({
                type: 'sync-health-warning',
                data: healthStatus,
                timestamp: now
            });
        }
        
        return healthStatus;
    }

    // 合并数值（求和）
    mergeSum(current, update) {
        if (typeof current === 'number' && typeof update === 'number') {
            return current + update;
        }
        
        if (typeof current === 'object' && typeof update === 'object') {
            const result = { ...current };
            for (const key in update) {
                if (typeof update[key] === 'number' && typeof result[key] === 'number') {
                    result[key] += update[key];
                } else {
                    result[key] = update[key];
                }
            }
            return result;
        }
        
        return update; // 默认使用新值
    }

    // 合并数值（平均值）
    mergeAverage(current, update) {
        if (typeof current === 'number' && typeof update === 'number') {
            return (current + update) / 2;
        }
        
        // 对于对象，使用替换策略
        return update;
    }

    // 显示冲突解决界面
    showConflictResolutionUI(conflict, update) {
        // 创建冲突解决对话框
        const dialog = document.createElement('div');
        dialog.className = 'conflict-resolution-dialog';
        dialog.innerHTML = `
            <div style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); 
                         background: white; padding: 20px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.3);
                         z-index: 1000; max-width: 500px; width: 90%;">
                <h3 style="margin: 0 0 15px 0; color: #e74c3c;">数据冲突</h3>
                <p style="margin: 0 0 10px 0;">检测到数据冲突，请选择要保留的值：</p>
                <div style="margin: 15px 0;">
                    <label style="display: block; margin-bottom: 5px;">
                        <input type="radio" name="conflict-resolution" value="current" checked>
                        当前值: ${JSON.stringify(conflict.currentValue)}
                    </label>
                    <label style="display: block; margin-bottom: 5px;">
                        <input type="radio" name="conflict-resolution" value="update">
                        新值: ${JSON.stringify(update.value)}
                    </label>
                </div>
                <div style="display: flex; gap: 10px; justify-content: flex-end;">
                    <button onclick="this.parentElement.parentElement.remove()" 
                            style="padding: 8px 16px; border: 1px solid #ddd; background: white; border-radius: 4px; cursor: pointer;">
                        取消
                    </button>
                    <button onclick="syncSystem.resolveManualConflict('${conflict.path}', this)" 
                            style="padding: 8px 16px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">
                        确认
                    </button>
                </div>
            </div>
        `;
        
        document.body.appendChild(dialog);
    }

    // 手动解决冲突
    resolveManualConflict(path, button) {
        const dialog = button.closest('.conflict-resolution-dialog');
        const selectedValue = dialog.querySelector('input[name="conflict-resolution"]:checked').value;
        
        // 这里需要实现具体的解决逻辑
        console.log('手动解决冲突:', path, selectedValue);
        
        dialog.remove();
    }

    // 获取性能指标
    getPerformanceMetrics() {
        return {
            subscriberCount: this.dataManager ? Object.keys(this.dataManager.subscribers).length : 0,
            updateQueueSize: this.syncHistory.length,
            stateSize: JSON.stringify(this.dataManager ? this.dataManager.state : {}).length,
            lastSync: this.syncHistory.length > 0 ? 
                this.syncHistory[this.syncHistory.length - 1].timestamp : null,
            healthStatus: this.checkSyncHealth()
        };
    }

    // 销毁系统
    destroy() {
        if (this.broadcastChannel) {
            this.broadcastChannel.close();
        }
        
        // 清理订阅
        this.syncChannels.clear();
        this.syncHistory = [];
    }
}

// 创建全局同步系统实例
let syncSystem;

// 初始化函数
function initSyncSystem() {
    syncSystem = new SyncSystem();
    // 导出到全局作用域
    window.syncSystem = syncSystem;
    console.log('同步系统已初始化');
}

// 页面加载完成后初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initSyncSystem);
} else {
    initSyncSystem();
}